import { Form, Input, Modal, TreeSelect, Switch } from 'antd'
import PropTypes from 'prop-types'
import { findOneMenu, createMenu, updateMenu } from '@/api/menu'
import { useEffect } from 'react'

const MenuForm = (props) => {
  const [form] = Form.useForm()

  useEffect(() => {
    async function fetchData () {
      if (props.menu_id) {
        const { data } = await findOneMenu({
          id: props.menu_id
        })

        form.setFieldsValue(data)
      }
    }
    fetchData()
  }, [props.menu_id])

  const onOk = async () => {
    const values = await form.validateFields()
    if (props.menu_id) {
      //更新
      await updateMenu({
        id: props.menu_id,
        ...values
      })
    } else {
      //新增
      await createMenu(values)
    }
    props.onOk()
  }

  const isDetail = Boolean(props.title.includes('详情'))
  return (
    <Modal
      title={props.title}
      open={props.visible}
      maskClosable={false}
      footer={isDetail ? null : undefined}
      cancelText="取消"
      okText="确定"
      onCancel={props.onCancel}
      onOk={onOk}
    >
      <Form
        form={form}
        autoComplete="off"
        disabled={isDetail}
        labelCol={{ span: 4 }}
      >
        <Form.Item
          name="name"
          label="菜单名称"
          rules={[
            {
              required: true,
              message: '菜单名称'
            }
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="code"
          label="菜单编码"
          rules={[
            {
              required: true,
              message: '菜单编码'
            }
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item name="path" label="菜单路径">
          <Input />
        </Form.Item>
        <Form.Item name="level" label="菜单层级">
          <Input placeholder='菜单层级必须填对，不然菜单生成有问题' />
        </Form.Item>
        <Form.Item name="parent_id" label="父级菜单">
          <TreeSelect
            showSearch
            allowClear
            treeNodeFilterProp='name'
            fieldNames={{
              label: 'name',
              value: 'menu_id',
              children: 'children'
            }}
            treeData={props.treeData}
          />
        </Form.Item>
        <Form.Item name="description" label="描述">
          <Input />
        </Form.Item>
        <Form.Item name="icon" label="菜单图标">
          <Input />
        </Form.Item>
        <Form.Item name="sort_order" label="排序">
          <Input />
        </Form.Item>
        <Form.Item name="is_visible" label="是否显示">
          <Switch checkedChildren="显示" unCheckedChildren="隐藏" defaultChecked />
        </Form.Item>
      </Form>
    </Modal>
  )
}

MenuForm.propTypes = {
  menu_id: PropTypes.number,
  title: PropTypes.string.isRequired,
  treeData: PropTypes.array.isRequired,
  visible: PropTypes.bool.isRequired,
  onCancel: PropTypes.func.isRequired,
  onOk: PropTypes.func.isRequired
}

export default MenuForm